package com.hulk.dryad.web.service.impl;


import cn.ms.sequence.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.constant.enums.*;
import com.hulk.dryad.common.exception.BaseRteException;
import com.hulk.dryad.common.util.IDWorkerRadix;
import com.hulk.dryad.common.util.PasswordEncoderFactoriesUtil;
import com.hulk.dryad.common.util.SaltGenerator;
import com.hulk.dryad.manage.provider.transaction.CustomerTransaction;
import com.hulk.dryad.persistence.entity.CustomerLoginInfo;
import com.hulk.dryad.persistence.entity.CustomerOperator;
import com.hulk.dryad.manage.provider.service.impl.CustomerLoginInfoServiceImpl;
import com.hulk.dryad.manage.provider.service.impl.CustomerOperatorServiceImpl;
import com.hulk.dryad.web.api.vo.CustomerLoginRespVO;
import com.hulk.dryad.web.api.vo.CustomerSocialLoginReqVO;
import com.hulk.dryad.web.service.OAuth2Service;
import com.xkcoding.justauth.AuthRequestFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;



/**
 * @author lqx
 */

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class OAuth2ServiceImpl implements OAuth2Service {

    private final AuthRequestFactory factory;
    private final CustomerLoginInfoServiceImpl customerLoginInfoServiceImpl;
    private final CustomerOperatorServiceImpl customerOperatorServiceImpl;
    private final CustomerTransaction customerTransaction;


    @Override
    public CustomerLoginRespVO manualAuth(CustomerSocialLoginReqVO reqVo) {
        String workId = IdWorker.getId() + "";
        log.info("workId:[{}] 授权登陆,入参:[{}]", workId, reqVo);
        AuthResponse response;
        CustomerLoginRespVO respDto;
        CustomerOperator operatorInfo;
        try {
            AuthRequest authRequest = factory.get(reqVo.getLoginType());
            AuthCallback callback = new AuthCallback();
            callback.setCode(reqVo.getSocialCode());
            callback.setState(reqVo.getSocialState());
            response = authRequest.login(callback);
            AuthUser user = (AuthUser) response.getData();
            CustomerLoginInfo loginInfo = customerLoginInfoServiceImpl.getOne(Wrappers.<CustomerLoginInfo>lambdaQuery()
                    .eq(CustomerLoginInfo::getLoginNo, user.getUuid()).eq(CustomerLoginInfo::getLoginType,reqVo.getLoginType()));
            if (null == loginInfo) {

                String operatorNo = IDWorkerRadix.getDTMId();
				/* 密码加密盐*/
                String passSalt = SaltGenerator.generateSalt();
                String loginPassword = "defaultpass";
				 /* 登陆信息*/
                loginInfo = new CustomerLoginInfo();
                loginInfo.setId(IdWorker.getId());
				loginInfo.setLoginNo(user.getUuid());
				loginInfo.setLoginType(reqVo.getLoginType());
                loginInfo.setOperatorNo(operatorNo);
                loginInfo.setLoginSignChannel("OTHER");
                loginInfo.setLoginStatus(CustomerLoginStatus.NORMAL.getType());
                loginInfo.setCreatedTime(LocalDateTime.now());
                loginInfo.setCreatedBy(CommonConstants.DEFUAULT_CREATER);
                /* 操作员信息*/
                operatorInfo = new CustomerOperator();
                operatorInfo.setId(IdWorker.getId());
                operatorInfo.setOperatorNo(operatorNo);
                operatorInfo.setOperatorName(user.getUsername());
                operatorInfo.setOperatorLvl(OperatorLevel.NOVICE.getType());
                operatorInfo.setNickName(user.getNickname());
                operatorInfo.setLoginPwd(PasswordEncoderFactoriesUtil.encode(loginPassword));
                operatorInfo.setLoginSalt(passSalt);
                operatorInfo.setRealnameStatus(YNFlag.N.getCode());
                operatorInfo.setLoginRightRange(OperatorLoginRange.ALL.getType());
                operatorInfo.setIdentity(null);
                operatorInfo.setOperatorStatus(OperatorStatus.NORMAL.getType());
                operatorInfo.setDataSourceType(OperatorSource.NORMAL.getType());
                operatorInfo.setPwdCreateType(PwdCreateType.CUSTOMER.getType());
                operatorInfo.setCreatedBy(CommonConstants.DEFUAULT_CREATER);
                operatorInfo.setCreatedTime(LocalDateTime.now());
                operatorInfo.setRsv1(RandomStringUtils.randomAlphabetic(32));
                customerTransaction.insertCustomerRelates(workId, loginInfo, operatorInfo);
            } else {
                operatorInfo = customerOperatorServiceImpl.getOne(Wrappers.<CustomerOperator>lambdaQuery()
                        .eq(CustomerOperator::getOperatorNo, loginInfo.getOperatorNo()));
                if (null == operatorInfo) {
                    throw new BaseRteException(BEC.E_2015);
                }
            }
			respDto = new CustomerLoginRespVO();
			respDto.setOperatorNo(operatorInfo.getOperatorNo());
			respDto.setLoginPwd(operatorInfo.getLoginPwd());
			respDto.setNickName(operatorInfo.getNickName());
			respDto.setAvatar(operatorInfo.getAvatar());
        } catch (BaseRteException ex) {
            log.error("workId:[{}] 授权登陆,异常:[{}]", workId, ex);
            throw ex;
        } catch (Exception e) {
            log.error("workId:[{}] 授权登陆,异常:[{}]", workId, e);
            throw new BaseRteException(BEC.E_9999);
        }
        log.info("workId:[{}] 授权登陆,返回:[{}]", workId, respDto);
        return respDto;
    }




}